<script setup lang="ts">
import { addRoleAPI, getRoleEditAPI, getTreeListAPI, updateRoleUserAPI } from '@/apis/system';
import type { RoleAddParams, RoleData, RoleUserData } from '@/types/system';
import { ElMessage, type FormInstance, type FormRules,  } from 'element-plus';
import type { TreeInstance } from 'element-plus/lib/components/index.js';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// 当前激活的步骤
const activeStep = ref(1)


// 添加角色检验
const roleForm=ref<RoleAddParams>({
    roleName:'',
    remark:'',
    perms:[]
  })
// 上一步
const prevStep = () => {
  activeStep.value--
}
// 下一步
// 表单校验属性
const treeRefs = ref<TreeInstance[]>([])
const nextStep = async () => {
//   表单校验1
    if(activeStep.value===1){
        roleFormRef.value?.validate((valid)=>{
            if(valid){
                activeStep.value++
            }
        })
    }
    // 表单校验2
    else if(activeStep.value===2){
        roleForm.value.perms=[];
        // 遍历树形组件，获取所有选中节点的 key 值
        treeRefs.value.forEach((tree)=>{
            const arrKeys = tree.getCheckedKeys() as number[];
            //存储进  
            roleForm.value.perms.push(arrKeys);  
        })
        // 把二维数组转扁平化，再判断长度
        if (roleForm.value.perms.flat().length === 0) {
            ElMessage.error("请角色的选择权限");
        } else {
            // 步骤增加
            activeStep.value++;  
        }
    }
  
}
   //表单校验
const roleFormRules=ref<FormRules<RoleAddParams>>({
  roleName:[{required:true,message:'请输入角色名称',trigger:'blur'}],
  remark:[{required:true,message:'请输入角色描述',trigger:'blur'}]
})  

const  roleFormRef=ref<FormInstance>()

// 获取树形结构
 // 3. 获取权限列表
 const treeList = ref<RoleData[]>([])

const getTreeList = async () => {
  const res = await getTreeListAPI()
  treeList.value = res.data
  
}
getTreeList()

//获取路由
const router=useRouter()
const route=useRoute()
// 点击确定添加
const onSubmit = async () => {
  //判断路由是否有ID
  const roleId=route.params.id
  if(roleId){
    // 有id就是编辑
    await updateRoleUserAPI(roleForm.value)
    ElMessage.success('编辑完成')
  }else{
    await addRoleAPI(roleForm.value)
    ElMessage.success('添加完成')
  }
  
//   跳转
  router.back()
}
// 编辑回显
const roleEdit=ref<RoleUserData
>()
const getRoleEdit=async()=>{
  if(route.params.id){
    const res=await getRoleEditAPI(Number(route.params.id))
    console.log(res);
    roleEdit.value=res.data
  }
  
}
getRoleEdit()
</script>

<template>
 
  <div class="add-role">
    <header class="add-header">
      <el-page-header :content="route.params.id?'编辑角色':'添加角色'" @back="$router.back()" />=
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div class="form-container" v-show="activeStep===1">
        <div class="title">角色信息</div>
        <el-form :model="roleForm" :rules="roleFormRules" ref="roleFormRef">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
                <el-input v-model="roleForm.remark" placeholder="请输入角色描述" />
            </el-form-item>
        </el-form>
        
      </div>
      <div class="form-container" v-show="activeStep===2">
        <div class="title">权限配置</div>
        <div class="form">
            <div class="tree-wrapper">
      <div v-for="(item,index) in treeList" :key="item.id" class="tree-item">
        <div class="tree-title">{{ item.title }}</div>
        <el-tree 
          :data="item.children" 
          show-checkbox 
          default-expand-all 
          node-key="id"
          :props="{ label: 'title' }" 
          ref="treeRefs" 
          :default-checked-keys="roleEdit.perms[index]"
        />
      </div>
    </div>
     </div>    
      </div>
      <!-- 检查并完成 -->
      <div class="form-container" v-show="activeStep===3">
        <div class="title">检查并完成</div>
        <div class="form">
            <div class="info">
        <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
        <div class="form-item">角色描述：{{ roleForm.remark }}</div>
        <div class="form-item">角色权限：</div>
        <div class="tree-wrapper">
          <div v-for="(item,index) in treeList" :key="item.id" class="tree-item">
            <div class="tree-title">{{ item.title }}</div>
            <el-tree
              :data="item.children"
              show-checkbox
              default-expand-all
              node-key="id"
              :props="{ label: 'title', disabled: () => true }"
              ref="diabledTreeRefs"
              :default-checked-keys="roleForm.perms[index]"
            />
          </div>
        </div>
      </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-if="activeStep!==1" @click="prevStep">上一步</el-button>
        <el-button v-if="activeStep!==3" type="primary" @click="nextStep">下一步</el-button>
        <el-button  v-if="activeStep===3" type="primary" @click="onSubmit">确认添加</el-button>
      </div>
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 30px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>